﻿using Avalonia;
using FantomNext.Controls;
using System.Linq;

namespace FantomNext.Presenters
{
    // ShapeDragMove
    public partial class ScenePresenter
    {
        #region fields
        private Point _shapeDragMoveOffsetPoint;
        #endregion

        #region methods
        private void ConfigShapePresenterView(FantomShape view)
        {
            view.PointerPressed += View_PointerPressed;
            view.PointerMoved += View_PointerMoved;
            view.PointerReleased += View_PointerReleased;
        }

        private void View_PointerPressed(object? sender, Avalonia.Input.PointerPressedEventArgs e)
        {
            var shape = sender as FantomShape;
            if (shape is null) return;
            var currentPoint = e.GetCurrentPoint(shape);
            _shapeDragMoveOffsetPoint = currentPoint.Position;
        }

        private void View_PointerMoved(object? sender, Avalonia.Input.PointerEventArgs e)
        {
            var shape = sender as FantomShape;
            if (shape is null) return;
            var currentPoint = e.GetCurrentPoint(View);
            if (currentPoint.Properties.IsLeftButtonPressed == false) return;

            // 左键按住拖拽时进行效果的处理。
            var shapePresenter = GetShapePresenter(shape);

            var scenePoint = ConvertVisualPointToScenePoint(currentPoint.Position);
            var finalScenePoint = scenePoint - _shapeDragMoveOffsetPoint;

            // 更新图形位置。
            shapePresenter.ScenePosition = new Shared.Vector2(finalScenePoint.X, finalScenePoint.Y);
            //shapePresenter.View currentPoint.Position

            var selectionFrameShapePresenterPair = GetSelectionFrameShapePresenterPair(shapePresenter);
            VisualizeSelectionFrame(selectionFrameShapePresenterPair);
        }

        private void View_PointerReleased(object? sender, Avalonia.Input.PointerReleasedEventArgs e)
        {

        }

        /// <summary>
        /// 获得当前可视的图形对象对应的Presenter上级管理对象。
        /// 目前使用的是非常简单的查询方法。
        /// </summary>
        /// <param name="fantomShape"></param>
        /// <returns></returns>
        private ShapePresenter GetShapePresenter(FantomShape fantomShape) => _shapes.FirstOrDefault(i => i.View == fantomShape);

     
        #endregion

    }
}
